//
//  UIButtonExtension.swift
//  Kool Car
//
//  Created by huangweiqiang on 2022/4/16.
//
//  UIButton 的点击事件用block回调处理

import UIKit

extension UIButton {
    private struct AssociatedKey {
        static var aIdentifier: String = "aIdentifier"
    }
    typealias ClickBlock = (Any) -> Void
    
    var returnBlock: ClickBlock {
        set {
            objc_setAssociatedObject(self, &AssociatedKey.aIdentifier, newValue, .OBJC_ASSOCIATION_COPY)
        }
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.aIdentifier) as! UIButton.ClickBlock
        }
    }
    
    func addTargetUsingBlock(aBlock: @escaping ClickBlock) {
        self.returnBlock = aBlock
        self.addTarget(self, action: #selector(self.xtClickAction(sender:)), for: .touchUpInside)
    }
    
    @objc func xtClickAction(sender: Any){
        self.returnBlock(sender)
    }
    
    func setup_titleLabel(text: String) {
        self.setTitle(text, for: .normal)
        self.setTitle(text, for: .highlighted)
    }
    
    func setup_titleColor(color: UIColor) {
        self.setTitleColor(color, for: .normal)
        self.setTitleColor(color, for: .highlighted)
    }
    
    func setup_image(image: UIImage? = nil) {
        guard image != nil else {
            return
        }
        self.setImage(image, for: .normal)
        self.setImage(image, for: .highlighted)
    }
    
    func setup_backgroundImage(image: UIImage? = nil) {
        self.setBackgroundImage(image, for: .normal)
        self.setBackgroundImage(image, for: .highlighted)
    }
}
